<template>
  <div class="template-preview">
    <!-- 预览工具栏 -->
    <div class="preview-toolbar" v-if="mode !== 'generate'">
      <div class="toolbar-left">
        <span class="preview-title">{{ template.name }}</span>
        <el-tag size="small">{{ getPageSizeText(template.pageSize) }}</el-tag>
        <el-tag size="small" :type="getTemplateTypeTag(template.type)">
          {{ getTemplateTypeText(template.type) }}
        </el-tag>
      </div>
      <div class="toolbar-right">
        <el-button-group size="mini">
          <el-button 
            :type="zoomLevel === 0.8 ? 'primary' : ''" 
            @click="setZoom(0.8)"
          >
            80%
          </el-button>
          <el-button 
            :type="zoomLevel === 1 ? 'primary' : ''" 
            @click="setZoom(1)"
          >
            100%
          </el-button>
          <el-button 
            :type="zoomLevel === 1.2 ? 'primary' : ''" 
            @click="setZoom(1.2)"
          >
            120%
          </el-button>
        </el-button-group>
        <el-button 
          size="mini" 
          icon="el-icon-full-screen" 
          @click="toggleFullscreen"
          class="fullscreen-btn"
        >
          {{ isFullscreen ? '退出全屏' : '全屏' }}
        </el-button>
      </div>
    </div>

    <!-- 预览内容 -->
    <div 
      class="preview-container" 
      :class="{ 'fullscreen': isFullscreen }"
      :style="containerStyle"
    >
      <div 
        class="preview-content" 
        :style="contentStyle"
        id="previewContent"
      >
        <template-renderer
          :components="template.components"
          :config="config"
          :mode="mode"
          :test-data="testData"
          @component-click="handleComponentClick"
        />
      </div>
    </div>

    <!-- 组件信息面板 -->
    <div v-if="selectedComponent && mode === 'preview'" class="component-info-panel">
      <div class="info-header">
        <h4>组件信息</h4>
        <el-button 
          type="text" 
          icon="el-icon-close" 
          @click="selectedComponent = null"
        ></el-button>
      </div>
      <div class="info-content">
        <el-descriptions :column="1" size="mini" border>
          <el-descriptions-item label="组件类型">
            {{ getComponentTypeText(selectedComponent.type) }}
          </el-descriptions-item>
          <el-descriptions-item label="位置尺寸">
            {{ selectedComponent.position.x }}px, {{ selectedComponent.position.y }}px
            ({{ selectedComponent.position.width }}×{{ selectedComponent.position.height }})
          </el-descriptions-item>
          <el-descriptions-item label="内容" v-if="selectedComponent.content">
            <pre class="content-preview">{{ JSON.stringify(selectedComponent.content, null, 2) }}</pre>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </div>
  </div>
</template>

<script>
import TemplateRenderer from './TemplateRenderer.vue'

export default {
  name: 'TemplatePreview',
  components: {
    TemplateRenderer
  },
  props: {
    template: {
      type: Object,
      required: true,
      default: () => ({
        name: '',
        type: 'record',
        pageSize: 'A4',
        components: []
      })
    },
    config: {
      type: Object,
      default: () => ({})
    },
    testData: {
      type: Object,
      default: () => ({})
    },
    mode: {
      type: String,
      default: 'preview' // preview, generate
    }
  },
  data() {
    return {
      zoomLevel: 1,
      isFullscreen: false,
      selectedComponent: null
    }
  },
  computed: {
    containerStyle() {
      if (this.isFullscreen) {
        return {
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          zIndex: 9999,
          backgroundColor: 'white'
        }
      }
      return {
        maxHeight: '70vh',
        overflow: 'auto'
      }
    },
    contentStyle() {
      const baseStyle = {
        transform: `scale(${this.zoomLevel})`,
        transformOrigin: 'top center',
        margin: '0 auto',
        backgroundColor: 'white',
        boxShadow: this.mode === 'preview' ? '0 4px 12px rgba(0, 0, 0, 0.15)' : 'none'
      }

      // 根据页面尺寸设置宽度
      const pageSizeStyles = {
        A4: { width: '210mm', minHeight: '297mm', padding: '10mm' },
        A3: { width: '297mm', minHeight: '420mm', padding: '10mm' },
        custom: { width: '100%', minHeight: '400px', padding: '20px' }
      }

      const pageStyle = pageSizeStyles[this.template.pageSize] || pageSizeStyles.A4
      return { ...baseStyle, ...pageStyle }
    }
  },
  methods: {
    /**
     * 获取页面尺寸文本
     */
    getPageSizeText(pageSize) {
      const sizeMap = {
        A4: 'A4',
        A3: 'A3',
        custom: '自定义'
      }
      return sizeMap[pageSize] || pageSize
    },

    /**
     * 获取模板类型标签样式
     */
    getTemplateTypeTag(type) {
      const tagMap = {
        record: 'primary',
        report: 'success'
      }
      return tagMap[type] || 'info'
    },

    /**
     * 获取模板类型文本
     */
    getTemplateTypeText(type) {
      const textMap = {
        record: '原始记录',
        report: '检测报告'
      }
      return textMap[type] || '未知类型'
    },

    /**
     * 获取组件类型文本
     */
    getComponentTypeText(type) {
      const typeMap = {
        text: '文本',
        table: '表格',
        parameter: '参数',
        image: '图片',
        header: '页眉',
        footer: '页脚',
        signature: '签名'
      }
      return typeMap[type] || type
    },

    /**
     * 设置缩放级别
     */
    setZoom(level) {
      this.zoomLevel = level
    },

    /**
     * 切换全屏模式
     */
    toggleFullscreen() {
      this.isFullscreen = !this.isFullscreen
      if (this.isFullscreen) {
        document.body.style.overflow = 'hidden'
      } else {
        document.body.style.overflow = ''
      }
    },

    /**
     * 处理组件点击
     */
    handleComponentClick(component) {
      if (this.mode === 'preview') {
        this.selectedComponent = component
      }
    },

    /**
     * 获取预览内容HTML（用于打印或导出）
     */
    getPreviewHTML() {
      const contentElement = document.getElementById('previewContent')
      return contentElement ? contentElement.innerHTML : ''
    },

    /**
     * 打印预览
     */
    print() {
      const originalBody = document.body.innerHTML
      const previewContent = this.getPreviewHTML()
      
      document.body.innerHTML = `
        <!DOCTYPE html>
        <html>
          <head>
            <title>${this.template.name}</title>
            <style>
              body { 
                margin: 0; 
                padding: 0; 
                font-family: "Microsoft YaHei", sans-serif;
              }
              .template-component { 
                position: relative !important; 
                page-break-inside: avoid;
              }
              @media print {
                @page { size: A4; margin: 0; }
                body { margin: 0; }
              }
            </style>
          </head>
          <body>${previewContent}</body>
        </html>
      `
      
      window.print()
      document.body.innerHTML = originalBody
      window.location.reload()
    }
  },
  beforeDestroy() {
    // 清理全屏状态
    if (this.isFullscreen) {
      document.body.style.overflow = ''
    }
  }
}
</script>

<style scoped>
.template-preview {
  position: relative;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.preview-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background: #f8f9fa;
  border-bottom: 1px solid #e6e8eb;
  flex-shrink: 0;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.preview-title {
  font-weight: 600;
  color: #303133;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.fullscreen-btn {
  margin-left: 10px;
}

.preview-container {
  flex: 1;
  padding: 20px;
  background: #f0f2f5;
  overflow: auto;
  display: flex;
  justify-content: center;
}

.preview-container.fullscreen {
  padding: 0;
  background: white;
}

.preview-content {
  transition: transform 0.3s ease;
  background: white;
}

.component-info-panel {
  position: absolute;
  right: 20px;
  top: 60px;
  width: 300px;
  background: white;
  border: 1px solid #e6e8eb;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  border-bottom: 1px solid #e6e8eb;
  background: #fafafa;
}

.info-header h4 {
  margin: 0;
  font-size: 14px;
  color: #303133;
}

.info-content {
  padding: 15px;
  max-height: 400px;
  overflow-y: auto;
}

.content-preview {
  font-size: 12px;
  background: #f8f9fa;
  padding: 8px;
  border-radius: 2px;
  margin: 0;
  max-height: 200px;
  overflow-y: auto;
  white-space: pre-wrap;
  word-break: break-all;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .preview-toolbar {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }

  .toolbar-right {
    width: 100%;
    justify-content: space-between;
  }

  .component-info-panel {
    position: relative;
    right: auto;
    top: auto;
    width: 100%;
    margin-top: 15px;
  }
}

/* 打印样式 */
@media print {
  .preview-toolbar,
  .component-info-panel {
    display: none !important;
  }

  .preview-container {
    padding: 0 !important;
    background: white !important;
  }

  .preview-content {
    transform: none !important;
    box-shadow: none !important;
    width: 100% !important;
    min-height: auto !important;
  }
}
</style>